package cn.yto.print.config.i18n;

import javafx.beans.binding.StringBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;


public class I18nResourceManager {

    private static final I18nResourceManager INSTANCE = new I18nResourceManager();
    private final ObjectProperty<Locale> currentLocaleProperty = new SimpleObjectProperty<>();

    private final BooleanProperty resourceBundleUpdateFlag = new SimpleBooleanProperty(true);
    private final String baseResourceName = "i18n/messages";

    private ResourceBundle appResourceBundle;

    private I18nResourceManager() {
        currentLocaleProperty.set(Locale.getDefault());
        refreshResourceBundle();
        // 注册语言环境变化监听器
        currentLocaleProperty.addListener((observable, oldLocale, newLocale) -> {
            refreshResourceBundle();
            resourceBundleUpdateFlag.set(!resourceBundleUpdateFlag.get());
        });
    }

    public static I18nResourceManager getInstance() {
        return INSTANCE;
    }

    public ObjectProperty<Locale> localeProperty() {
        return currentLocaleProperty;
    }

    public Locale getCurrentLocale() {
        return currentLocaleProperty.get();
    }

    public void setLocale(Locale locale) {
        currentLocaleProperty.set(locale);
    }

    public ResourceBundle getResourceBundle() {
        return appResourceBundle;
    }

    private void refreshResourceBundle() {
        appResourceBundle = ResourceBundle.getBundle(baseResourceName, currentLocaleProperty.get());
    }

    /**
     * 获取字符串绑定
     */
    public StringBinding getStringBinding(String key) {
        return new StringBinding() {
            {
                bind(resourceBundleUpdateFlag);
            }

            @Override
            protected String computeValue() {
                return getResourceBundle().getString(key);
            }
        };
    }

    /**
     * 直接获取国际化字符串
     */
    public String get(String key) {
        try {
            return appResourceBundle.getString(key);
        } catch (MissingResourceException e) {
            return null;
        } catch (Exception e) {
            return null;
        }
    }

}